package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private FriendApi friendApi;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if(!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性

        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    public PageResult likeEachOther(Integer type, Integer page, Integer pagesize, String nickname) {
        // 获取当前用户userId
        Long userId = UserHolder.getUserId();
        PageResult pageResult = new PageResult();

        // 构建查询条件
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);

        if (type == 1) {
            // 互相喜欢 userId friendId = friendId userId
            pageResult = userLikeApi.findOtherLike(userId, page, pagesize);
            return getPageResult(pageResult, userInfo);
        } else if (type == 2) {
            // 单向喜欢
            pageResult = userLikeApi.findMyLike(userId, page, pagesize);
            return getPageResult(pageResult, userInfo);
        } else if (type == 3) {
            // 我的粉丝
            pageResult = userLikeApi.findLikeMe(userId, page, pagesize);
            List<UserLike> userLikes = (List<UserLike>) pageResult.getItems();
            if (CollectionUtils.isEmpty(userLikes)) {
                return pageResult;
            }

            List<Long> likeMeIds = userLikes.stream().map(UserLike::getUserId).collect(Collectors.toList());
            Map<Long, UserInfo> map = userInfoApi.findByIds(likeMeIds, userInfo);

            List<UserLikeVo> likeVos = userLikes.stream()
                    .filter(c -> map.get(c.getUserId()) != null)
                    .map(userLike -> {
                        UserLikeVo likeVo = UserLikeVo.init(map.get(userLike.getUserId()), null);
                        Boolean flag = isTogetherLike(userLike.getUserId(), userLike.getLikeUserId());
                        likeVo.setAlreadyLove(flag);
                        return likeVo;
                    }).collect(Collectors.toList());
            pageResult.setItems(likeVos);

            return pageResult;
        } else {
            // 谁看过我
            pageResult = visitorsApi.lookAtMe(userId, page, pagesize);
            List<Visitors> visitors = (List<Visitors>) pageResult.getItems();
            if (CollectionUtils.isEmpty(visitors)) {
                return pageResult;
            }

            List<Long> visitorsIds = visitors.stream().map(Visitors::getVisitorUserId).collect(Collectors.toList());
            Map<Long, UserInfo> map = userInfoApi.findByIds(visitorsIds, userInfo);

            List<UserLikeVo> likeVos = visitors.stream()
                    .filter(c -> map.get(c.getVisitorUserId()) != null)
                    .map(visitor -> UserLikeVo.init(map.get(visitor.getVisitorUserId()), visitor))
                    .collect(Collectors.toList());
            pageResult.setItems(likeVos);
            return pageResult;
        }
    }

    // true 相互喜欢   false 单向
    private Boolean isTogetherLike(Long userId, Long likeUserId) {
        UserLike userLike = userLikeApi.findOne(userId, likeUserId);
        return userLike != null;
    }

    private PageResult getPageResult(PageResult pageResult, UserInfo userInfo) {
        List<UserLike> userLikes = (List<UserLike>) pageResult.getItems();
        if (CollectionUtils.isEmpty(userLikes)) {
            return pageResult;
        }

        List<Long> myLikeIds = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        Map<Long, UserInfo> map = userInfoApi.findByIds(myLikeIds, userInfo);

        List<UserLikeVo> likeVos = userLikes.stream()
                .filter(c -> map.get(c.getLikeUserId()) != null)
                .map(userLike -> {
                    UserLikeVo likeVo = UserLikeVo.init(map.get(userLike.getLikeUserId()), null);
                    likeVo.setAlreadyLove(true);
                    return likeVo;
                }).collect(Collectors.toList());
        pageResult.setItems(likeVos);
        return pageResult;
    }

    /**
     * 粉丝喜欢
     * @param uid 粉丝id
     */
    public void fans(Long uid) {
        userLikeApi.saveOrUpdate(UserHolder.getUserId(), uid, true);
        friendApi.save(UserHolder.getUserId(), uid);
    }

    /**
     * 取消喜欢
     * @param uid
     */
    public void removeLike(Long uid) {
        Boolean flag = isTogetherLike(UserHolder.getUserId(), uid);
        if (flag) {
            userLikeApi.removeLike(UserHolder.getUserId(), uid);
            friendApi.deleteFriend(UserHolder.getUserId(), uid);
        } else {
            userLikeApi.removeLike(UserHolder.getUserId(), uid);
        }
    }
}
